/**
 * 
 */
package org.agiba.jira.plugin.action;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.agiba.jira.plugin.model.XWikiDocumentInfo;
import org.agiba.jira.plugin.model.XWikiInstance;
import org.agiba.jira.plugin.xwiki.XWikiRPCService;
import org.apache.commons.lang.StringUtils;

import com.atlassian.jira.web.action.JiraWebActionSupport;

/**
 * @author kamann
 *
 */
public class XWikiPageBrowserAction extends JiraWebActionSupport {
	private static final long serialVersionUID = 1L;
	private String searchQuery;
	private String instanceKey;
	private String space;
	private String customFieldId;
	private XWikiRPCService service;
	
	private String spaceKey = "";

	public XWikiPageBrowserAction(){
		service = new XWikiRPCService();
	}
	
	public List<XWikiDocumentInfo> findDocumentByQuery(){
		XWikiInstance instance = null;
		List<XWikiDocumentInfo> documents = new ArrayList<XWikiDocumentInfo>();
		
		if (StringUtils.isNotEmpty(instanceKey)){
			instance = service.findXWikiInstanceByKey(instanceKey);
		}
		
		if (instance != null){
			documents = service.findDocumentsByQuery(instance, space,
					searchQuery);
		}
		return documents;
	}

	public String doSearch() {
		if (spaceKey.contains(":")) {
			String[] tokens = spaceKey.split(":");
			instanceKey = tokens[0];
			space = tokens[1];
		}
		return SUCCESS;
	}

	
	public List<XWikiInstance> getXWikiInstances(){
		return service.findAllXwikiInstances();
	}
	
	/**
	 * @return the searchQuery
	 */
	public String getSearchQuery() {
		return searchQuery;
	}

	/**
	 * @param searchQuery the searchQuery to set
	 */
	public void setSearchQuery(String searchQuery) {
		try {
			new URL(searchQuery);
			this.searchQuery = "";
		} catch (MalformedURLException e) {
			this.searchQuery = searchQuery;
		}
	}

	/**
	 * @param instanceKey
	 *            the instanceKey to set
	 */
	public void setSpaceKey(String spaceKey) {
		this.spaceKey = spaceKey;
	}

	/**
	 * @return the spaceKey
	 */
	public String getSpaceKey() {
		return spaceKey;
	}

	/**
	 * @return the customFieldId
	 */
	public String getCustomFieldId() {
		return customFieldId;
	}

	/**
	 * @param customFieldId the customFieldId to set
	 */
	public void setCustomFieldId(String customFieldId) {
		this.customFieldId = customFieldId;
	}

}
